/**
 * Anderground project - Subway maps processor application.
 * Copyright (C) 2008-2009 Eldar Abusalimov, Ilya Shurigyn
 * 
 * This file is part of Anderground.
 * 
 * Anderground is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * Anderground is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Anderground.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.anderground.core.util;

import java.lang.ref.WeakReference;
import java.util.Observable;
import java.util.Observer;

/**
 * {@link Observable} with {@link WeakReference}s to its {@link Observer}s
 * 
 * @author Eldar Abusalimov (eldar.abusalimov@gmail.com)
 */
public class WeakObservable extends Observable {

	/** {@inheritDoc} */
	@Override
	public synchronized void addObserver(Observer o) {
		super.addObserver(new WeakObserverProxy(o));
	}

	/** {@inheritDoc} */
	@Override
	public synchronized void deleteObserver(Observer o) {
		super.deleteObserver(new WeakObserverProxy(o));
	}

	/**
	 * @author Eldar Abusalimov (eldar.abusalimov@gmail.com)
	 */
	private class WeakObserverProxy extends WeakReference<Observer> implements
			Observer {

		/**
		 * @param referent
		 */
		public WeakObserverProxy(Observer referent) {
			super(referent);
		}

		@Override
		public void update(Observable o, Object arg) {
			Observer observer = get();
			if (observer != null) {
				observer.update(o, arg);
			} else {
				o.deleteObserver(this);
			}
		}

		@Override
		public boolean equals(Object obj) {
			if (super.equals(obj)) {
				return true;
			}
			if (obj instanceof WeakObserverProxy) {
				WeakObserverProxy proxy = (WeakObserverProxy) obj;
				Observer thisObserver = get();
				Observer proxyObserver = proxy.get();
				if (thisObserver == null) {
					return proxyObserver == null;
				}
				return thisObserver.equals(proxyObserver);
			}
			return false;
		}

	}

}
